package com.app.util.memcached;

public class MemCachedTable {

	private final String name;
	private final MemCached memcached;

	public MemCachedTable(String name, MemCached memcached) {
		super();
		this.name = name;
		this.memcached = memcached;
	}

	private String makeKey(String key) {
		return name + key;
	}

	/**
	 * 添加一个指定的值到缓存中.
	 * 
	 * @param key
	 * @param value
	 * @param expirySec
	 * @return 
	 */
	public boolean set(String key, Object value) {
		boolean ok = memcached.set(makeKey(key), value, 5);
		// System.out.println(ok + " - MemCached(" + ok + "): " + name +
		// ".set(\"" + key + "\", String(" + value.toString().length() +
		// ")) not expires");
		return ok;
	}

	/**
	 * 添加一个指定的值到缓存中.
	 * 
	 * @param key
	 * @param value
	 * @param expirySec
	 * @return
	 */
	public boolean set(String key, Object value, long expirySec) {
		boolean ok = memcached.set(makeKey(key), value, expirySec);
		// System.out.println("MemCached(" + ok + "): " + name + ".set(\"" + key
		// + "\", String(" + value.toString().length() + ")) expires in " +
		// DateUtil.format(new Date(System.currentTimeMillis() + expirySec *
		// 1000), "yyyy/MM/dd HH:mm:ss"));
		return ok;
	}

	/**
	 * 删除一个指定的值到缓存中.
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean delete(String key) {
		boolean ok = memcached.delete(makeKey(key));
		// System.out.println("MemCached(" + ok + "): " + name + ".del(\"" + key
		// + "\")");
		return ok;
	}

	/**
	 * 根据指定的关键字获取对象.
	 * 
	 * @param key
	 * @return
	 */
	public Object get(String key) {
		return memcached.get(makeKey(key));
	}

	public String getName() {
		return name;
	}

	public MemCached getMemcached() {
		return memcached;
	}

}